import { defineComponent, ref, h, computed } from "vue";

export default defineComponent({
	name: "ContextMenu",
	inheritAttrs: false,
	props: {
		visible: Boolean
	},
	setup(props, { slots, attrs, expose, emit }) {
		const visible = ref(false);
		const leftPos = ref(0);
		const topPos = ref(0);
		const node = ref({});

		const styleComputed = computed(() => {
			return {
				left: leftPos.value + "px",
				top: topPos.value + "px"
			};
		});

		const onEdit = (command: string) => {
			emit("emitMenu", { command, currentNode: node.value });
			visible.value = false;
		};

		const closeModal = () => {
			if (visible.value) visible.value = false;
		};
		const showModal = (position: Record<string, any> = { left: 0, top: 0 }) => {
			node.value = position.node;
			leftPos.value = position.left;
			topPos.value = position.top;
			visible.value = true;
		};
		expose({
			showModal
		});

		const contextMenuClass =
			"w-28 p-2.5 fixed z-11 text-slate-600 bg-white shadow-xl border border-sllid border-gray-200";
		const itemClass =
			"select-none rounded-md p-2.5 cursor-pointer duration-200 hover:bg-sky-100 hover:text-sky-500";

		const ContextMenu = () => (
			<div class={contextMenuClass} style={styleComputed.value}>
				<div class={itemClass} onClick={() => onEdit("add")}>
					新增节点
				</div>
				<div class={itemClass} onClick={() => onEdit("edit")}>
					编辑节点
				</div>
				<div class={itemClass} onClick={() => onEdit("delete")}>
					删除节点
				</div>
			</div>
		);
		return () => <div v-click-outside={closeModal}>{visible.value ? ContextMenu() : ""}</div>;
	}
});
